package com.alibaba.org.service.impl;

import com.alibaba.basic.exception.BusinessException;
import com.alibaba.basic.query.BaseQuery;
import com.alibaba.basic.util.*;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.domain.Shop;
import com.alibaba.org.domain.ShopAuditLog;
import com.alibaba.org.dto.ShopEchartDto;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.mapper.ShopAuditLogMapper;
import com.alibaba.org.mapper.ShopMapper;
import com.alibaba.org.service.IShopService;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.mapper.LogininfoMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private  ShopAuditLogMapper shopAuditLogMapper;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private LogininfoMapper logininfoMapper;

    @Override
    public void settlement(Shop shop) {

        //非空判断
        if (StringUtils.isEmpty(shop.getName()) || StringUtils.isEmpty(shop.getTel())
                || StringUtils.isEmpty(shop.getAddress()) || StringUtils.isEmpty(shop.getAdmin().getUsername())
                || StringUtils.isEmpty(shop.getAdmin().getEmail()) || StringUtils.isEmpty(shop.getAdmin().getPhone())
                || StringUtils.isEmpty(shop.getAdmin().getPassword()) || StringUtils.isEmpty(shop.getAdmin().getComfirmPassword())
        ){
            //抛出业务异常
            throw new BusinessException("相关数据不可为空");
        }
        //密码一致性判断
        if (!shop.getAdmin().getPassword().equals(shop.getAdmin().getComfirmPassword())){
            throw new BusinessException("两次密码不一致");
        }
        //判断店铺的名字和用户名的名字是非违规(百度ai)
        if(!BaiduAuditUtils.TextCensor(shop.getName())||!BaiduAuditUtils.TextCensor(shop.getAdmin().getUsername())){
            throw new BusinessException("店铺名或用户名违法，请文明用语");
        }

        //查询 店铺 的名字 和 地址 如果数据库 有相同的 店铺 则抛出异常
        Shop tempShop = shopMapper.findByMessage(shop);
        //判断店铺是否已存在
        if (tempShop != null){
            throw new BusinessException("店铺已存在");
        }
        //判断管理员存在并且绑定过账号，抛出异常
         Employee temEmployee=employeeMapper.findByUsername(shop.getAdmin().getUsername());
        if (temEmployee != null && temEmployee.getShopId() != null){
            throw new BusinessException("该管理员已绑定店铺,请更换管理员");
        }
        // 5.管理员没注册，那么注册管理员
        if (temEmployee==null){
            Employee admin= shop.getAdmin();
            //加盐
            String salt = StrUtils.getComplexRandomString(32);
            admin.setSalt(salt);
            //加密(密码先加盐 然后加盐后的密码通过md5技术加密)
            String md5Pwd = MD5Utils.encrypByMd5(admin.getPassword() + salt);
            admin.setPassword(md5Pwd);
            employeeMapper.save(admin);
            Logininfo logininfo = new Logininfo();
            BeanUtils.copyProperties(admin,logininfo);
            logininfo.setType(0);
            logininfoMapper.save(logininfo);
        }

        //将店铺管理员id 设置为 管理员id
        shop.setAdminId(temEmployee.getId());
        shopMapper.save(shop);
        temEmployee.setShopId(shop.getId());
        employeeMapper.update(temEmployee);

    }

    /**
     * 通过店铺
     * @param shopAuditLog
     */
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        //修改店铺信息的状态为通过
        //保存日志信息
        shopAuditLog.setAuditId(325L); //写死
        shopAuditLogMapper.save(shopAuditLog);
        // 发送激活邮件给用户
    }

    /**
     * 驳回店铺
     * @param shopAuditLog
     */
    @Override
    public void reject(ShopAuditLog shopAuditLog , HttpServletRequest request) {

        // 1.从请求头中获取token，判断是否存在
        //String logininfo = request.getHeader("logininfo");
        // 1.1.不存在，返回一个{"success":false,"message":"noLogin"},再返回false
        // Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);


        //修改店铺信息的状态为驳回
        //保存日志信息
        shopAuditLog.setAuditId(shopAuditLog.getAuditId());
        shopAuditLog.setState(4);
        shopAuditLogMapper.save(shopAuditLog);
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(4);
        shopMapper.update(shop);

         Employee employee=employeeMapper.findByShopID(shopAuditLog.getShopId());
        String email = employee.getEmail();
        // 发送驳回邮件给用户
        // 3.发送修改店铺信息邮件给用户
        // 2.发送复杂邮件的工具类
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            //使用工具类来构建消息
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            //
            helper.setFrom("563977312@qq.com");
            //设置邮件主题
            helper.setSubject("审核失败通知");
            //邮件正文
            helper.setText("<h1>审核失败</h1><br>"+
                    "<span>失败原因："+shopAuditLog.getNote()+"</span><br>"+
                    "<a href='http://127.0.0.1:8081/#/register2?id="+shopAuditLog.getShopId()+"'>点击修改资料</a>",true);
            helper.setTo(email);
            //发送消息
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {

            e.printStackTrace();
        }

    }


    @Override
    public Map<String, Object> loadEcharts() {

        List<ShopEchartDto> shopEchartDtos =shopMapper.loadEcharts();
        List<Integer> states = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (ShopEchartDto shopEchartDto : shopEchartDtos) {
            states.add(shopEchartDto.getState());
            counts.add(shopEchartDto.getCount());
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("x", states);
        map.put("y", counts);
        return map;
    }

    @Override
    public PageList<Shop> queryPage(BaseQuery query) {


        //先查询总数量
        Long totals = shopMapper.queryCount(query);

        if(totals < 1){
            return new PageList<Shop>();
        }
        //再查询当前页的分页数据
        List<Shop> data = shopMapper.queryData(query);

        for (Shop shop : data) {
            List<ShopAuditLog> shopAuditLogs=shopAuditLogMapper.findById(shop.getId());
            for (ShopAuditLog shopAuditLog : shopAuditLogs) {
                shop.getShopAuditLogs().add(shopAuditLog);
            }
        }
        return new PageList<Shop>(totals,data);
    }
}
